<template>
  <section class="todoapp">
    <TodoListHeader @add="addList"></TodoListHeader>
    <TodoListMain
      :list="showList"
      @setFlag="setFlag"
      @delList="delList"
      @setAll="setAll"
    ></TodoListMain>
    <TodoListFooter
      :list="showList"
      :type="type"
      @delAll="delAll"
      @changeType="changeType"
    ></TodoListFooter>
  </section>
</template>

<script>
import TodoListHeader from './components/ToListHeader.vue'
import TodoListMain from './components/TodoListMain.vue'
import TodoListFooter from './components/TodoListFooter.vue'

export default {
  components: {
    TodoListHeader,
    TodoListMain,
    TodoListFooter
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [
        {
          id: 1,
          name: '读万卷书',
          flag: true
        },
        {
          id: 2,
          name: '行万里路',
          flag: false
        }
      ],
      type: 'all'
    }
  },
  methods: {
    addList(name) {
      this.list = [
        ...this.list,
        {
          id: +new Date(),
          name,
          flag: false,
          isEdit: false
        }
      ]
    },

    setFlag(flag, id) {
      this.list.forEach((item) => {
        if (item.id === id) item.flag = flag
      })
    },

    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },

    delAll() {
      this.list = this.list.filter((item) => !item.flag)
    },

    changeType(type) {
      this.type = type
    },

    setAll(value) {
      this.list.forEach((item) => (item.flag = value))
    }
  },
  watch: {
    list: {
      deep: true,
      handler(newval) {
        localStorage.setItem('list', JSON.stringify(newval))
      }
    }
  },
  computed: {
    showList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    }
  }
}
</script>

<style></style>
